<!--
 * @Descripttion: 编辑卡券
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2021-11-19 18:09:11
-->
<template>
  <div class="lb-add-redpackit">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="page-main">
      <el-form
        @submit.native.prevent
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
      >
        <el-form-item label="卡券类型" prop="coupon_type">
          <el-radio-group
            v-model="ruleForm.coupon_type"
            :disabled="ruleForm.id ? true : false"
            @change="redMarketChange($event, 'coupon_type')"
          >
            <el-radio :label="0">优惠券</el-radio>
            <el-radio :label="1">礼品券</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input
            v-model="ruleForm.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="使用条件" prop="use_limit">
          <el-radio-group
            v-model="ruleForm.use_limit"
            @change="redMarketChange($event, 'use_limit')"
          >
            <el-radio :label="0">消费满</el-radio>
            <el-radio :label="1">无门槛</el-radio>
          </el-radio-group>
        </el-form-item>
        <block
          v-if="ruleForm.coupon_type == 1 && ruleForm.use_limit == 1"
        ></block>
        <el-form-item prop="full" v-else>
          <block v-if="ruleForm.use_limit === 0">
            消费满
            <el-input
              el-input
              v-model.number="ruleForm.full"
              placeholder="请输入消费金额"
              style="width: 130px"
            ></el-input>
            元可用
          </block>
          <block v-if="ruleForm.coupon_type === 0">
            <block v-if="ruleForm.use_limit === 1">立减</block>
            <el-input
              v-model.number="ruleForm.reduce"
              placeholder="请输入优惠金额"
              style="width: 130px"
            ></el-input>
            元</block
          >
        </el-form-item>
        <el-form-item
          label="卡券数量"
          prop="number"
          v-if="ruleForm.send_type !== 2"
        >
          <el-input
            v-model.number="ruleForm.number"
            placeholder="请输入数量"
          ></el-input>
          <lb-tool-tips>每个员工发放卡券数量</lb-tool-tips>
        </el-form-item>
        <el-form-item label="活动规则" prop="activity_rules">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="ruleForm.activity_rules"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="ruleForm.coupon_type === 0 ? '优惠详情' : '兑换详情'"
          prop="content"
        >
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="ruleForm.content"
          ></el-input>
        </el-form-item>
        <el-form-item label="核销类型" prop="type">
          <el-radio-group
            v-model="ruleForm.type"
            @change="redMarketChange($event, 'type')"
          >
            <el-radio :label="1" v-if="ruleForm.coupon_type === 0"
              >线上{{ $t('menu.Malls') }}抵扣</el-radio
            >
            <el-radio :label="2">线下扫码核销</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="限用类型" prop="limit_type">
          <el-radio-group v-model="ruleForm.limit_type">
            <el-radio :label="0">无限用</el-radio>
            <el-radio v-if="ruleForm.type === 1" :label="1">限用分类</el-radio>
            <el-radio v-if="ruleForm.type === 1" :label="2">限用商品</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="ruleForm.limit_type === 1" prop="limit_cate">
          <el-cascader
            collapse-tags
            v-model="ruleForm.limit_cate"
            :options="disableOptions"
            :props="{
              multiple: true,
              checkStrictly: true,
              value: 'id',
              label: 'title'
            }"
            clearable
            placeholder="请选择分类"
          ></el-cascader>
        </el-form-item>
        <el-form-item v-if="ruleForm.limit_type === 2" prop="limit_goods">
          <el-select
            collapse-tags
            v-model="ruleForm.limit_goods"
            multiple
            filterable
            placeholder="请选择商品名称"
          >
            <el-option
              v-for="item in goodsOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="卡券限用" prop="company_limit">
          <el-radio-group v-model="ruleForm.company_limit">
            <el-radio :label="0">不限制</el-radio>
            <el-radio :label="1">指定公司/部门</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >勾选之后，只有被选中的公司/部门才有权限核销卡券</lb-tool-tips
          >
        </el-form-item>
        <el-form-item v-if="ruleForm.company_limit === 1" prop="company_id">
          <el-cascader
            collapse-tags
            v-model="ruleForm.company_id"
            :options="base_company"
            :props="{
              multiple: true,
              checkStrictly: true,
              value: 'id',
              label: 'name'
            }"
            clearable
            placeholder="请选择公司/部门"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="用券时间" prop="end_time_type">
          <el-radio-group v-model="ruleForm.end_time_type">
            <el-radio :label="0">指定日期</el-radio>
            <el-radio :label="1">有效天数</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label
          prop="start_time"
          v-if="ruleForm.end_time_type === 0"
        >
          <el-date-picker
            v-model="ruleForm.start_time"
            type="datetime"
            placeholder="选择开始日期时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label prop="end_time" v-if="ruleForm.end_time_type === 0">
          <el-date-picker
            v-model="ruleForm.end_time"
            type="datetime"
            placeholder="选择结束日期时间"
          ></el-date-picker>
          <lb-tool-tips>领取的卡券必须在该时间前使用</lb-tool-tips>
        </el-form-item>
        <el-form-item
          label
          prop="end_time_day"
          v-if="ruleForm.end_time_type === 1"
        >
          <em class="text-normal">自领券当日起</em>
          <el-input-number
            v-model="ruleForm.end_time_day"
            class="lb-input-number mini"
            :controls="false"
            :precision="0"
            :min="1"
          ></el-input-number>
          <em class="text-normal">天内可用</em>
          <lb-tool-tips
            >有效期按自然天计算。
            <div class="mt-sm mb-sm">
              举例：如设置领券当日起30天内可用，用户在5月18日14:00时领取优惠券，则该优惠券的可用时间为5月18日的14:00:00至6月18日的14:00
            </div>
            注意：时间按自然天来算，不是月
          </lb-tool-tips>
        </el-form-item>
        <el-form-item label="派发方式" prop="send_type">
          <el-radio-group
            v-model="ruleForm.send_type"
            :disabled="ruleForm.id ? true : false"
            @change="redMarketChange($event, 'send_type')"
          >
            <el-radio :label="0">用户领取</el-radio>
            <el-radio :label="1">员工手动派发</el-radio>
            <el-radio :label="2">系统自动派发</el-radio>
          </el-radio-group>
          <lb-tool-tips>
            <div v-if="ruleForm.send_type === 0">
              用户领取是指用户需领取后，卡券才能到用户的卡包，勾选之后卡券会展示在小程序端
            </div>
            <div v-if="ruleForm.send_type === 1">
              员工手动派发是指员工对某些用户定向发放卡券，该卡券一般不会展示在商城
            </div>
            <div v-if="ruleForm.send_type === 2">
              系统自动派发是指满足条件的某些用户，例如：会员（某些会员权益会以卡券形式自动派发到用户卡包里，无需用户领取）
            </div>
          </lb-tool-tips>
        </el-form-item>
        <el-form-item label="领取身份" prop="get_identity">
          <el-radio-group v-model="ruleForm.get_identity">
            <el-radio :label="0">不限制，所有人可领取</el-radio>
            <el-radio :label="1" v-if="ruleForm.send_type !== 2"
              >指定客户可领取</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="ruleForm.get_identity === 1" prop="user_id">
          <el-select
            v-model="ruleForm.user_id"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请选择指定客户"
          >
            <el-option
              v-for="item in base_user"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="每人限领次数" prop="time_limit">
          <el-radio-group v-model="ruleForm.time_limit">
            <el-radio :label="0">不限次数</el-radio>
            <el-radio :label="1" v-if="ruleForm.send_type === 0"
              >限制次数</el-radio
            >
          </el-radio-group>
          <lb-tool-tips>
            <p v-if="ruleForm.time_limit === 0">
              客户只能在每个员工处领取一次，可在多个员工处领取
            </p>
            <p v-if="ruleForm.time_limit === 1">
              例如：每人限领次数是5，则客户最多可在5个员工处领取
            </p>
          </lb-tool-tips>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.send_type === 0 && ruleForm.time_limit === 1"
          prop="get_time"
        >
          每人限领
          <el-input
            v-model.number="ruleForm.get_time"
            style="width: 100px"
          ></el-input>
          次
        </el-form-item>
        <el-form-item label="排序值" prop="top">
          <el-input-number
            class="lb-input-number"
            v-model="ruleForm.top"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入排序值"
          ></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitForm">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="goBack">{{ $t('action.back') }}</lb-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    let validateCate = (rule, value, callback) => {
      if (this.ruleForm.limit_type === 1) {
        if (value.length === 0) {
          callback(new Error('请选择限用分类'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let validateGoods = (rule, value, callback) => {
      if (this.ruleForm.limit_type === 2) {
        if (value.length === 0) {
          callback(new Error('请选择限用商品'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let validateCompany = (rule, value, callback) => {
      if (this.ruleForm.company_limit === 1) {
        if (value.length === 0) {
          callback(new Error('请选择公司/部门'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let validateStartTime = (rule, value, callback) => {
      if (this.ruleForm.end_time_type === 0) {
        if (value.length === 0) {
          callback(new Error('请选择开始时间'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let validateEndTime = (rule, value, callback) => {
      if (this.ruleForm.end_time_type === 0) {
        if (value.length === 0) {
          callback(new Error('请选择到期时间'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let valiDateNumber = (rule, value, callback) => {
      if (Number.isInteger(value)) {
        callback()
      } else {
        callback(new Error('请输入数字类型'))
      }
    }
    let validateUser = (rule, value, callback) => {
      if (this.ruleForm.get_identity === 1) {
        if (value.length === 0) {
          callback(new Error('请选择指定客户'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let validateGetTime = (rule, value, callback) => {
      if (this.ruleForm.send_type === 0 && this.ruleForm.time_limit === 1) {
        if (!/^(([1-9][0-9]*))$/.test(value)) {
          callback(new Error('请输入每人限制次数'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let validateFull = (rule, value, callback) => {
      if (this.ruleForm.use_limit === 0) {
        if (!/^(([1-9][0-9]*))$/.test(value)) {
          callback(new Error('请输入消费金额'))
        } else {
          if (this.ruleForm.coupon_type === 0) {
            if (!/^(([1-9][0-9]*))$/.test(this.ruleForm.reduce)) {
              callback(new Error('请输入优惠金额'))
            } else if (value * 1 < this.ruleForm.reduce * 1) {
              callback(new Error('优惠金额不能大于消费金额'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
      } else if (this.ruleForm.use_limit === 1) {
        if (this.ruleForm.coupon_type === 1) {
          callback()
        } else if (!/^(([1-9][0-9]*))$/.test(this.ruleForm.reduce)) {
          callback(new Error('请输入优惠金额'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      tips_fafang: `选择立即发放，客户进入${this.$t(
        'menu.BusinessCard'
      )}就能领取, 领取后不可修改`,
      navTitle: '',
      ruleForm: {
        id: 0,
        title: '',
        full: '',
        reduce: '',
        type: 1,
        activity_rules: '',
        number: 1,
        limit_type: 0,
        limit_cate: [],
        limit_goods: [],
        company_id: [],
        end_time_type: 0,
        end_time_day: 1,
        end_time: '',
        start_time: '',
        company_limit: 0,
        coupon_type: 0,
        use_limit: 0,
        send_type: 0,
        get_identity: 0,
        user_id: [],
        time_limit: 0,
        get_time: 1,
        content: '',
        top: 0
      },
      rules: {
        title: { required: true, message: '请输入标题', trigger: 'blur' },
        type: { required: true, message: '请选择卡券类型', trigger: 'change' },
        number: [
          {
            required: true,
            message: '请输入数量',
            validator: valiDateNumber,
            trigger: 'blur'
          }
        ],
        status: {
          required: true,
          message: '请选择发放类型',
          trigger: 'change'
        },
        limit_type: {
          required: true,
          message: '请选择卡券限用',
          trigger: 'change'
        },
        company_limit: {
          required: true,
          message: '请选择指定公司/部门',
          trigger: 'change'
        },
        end_time_type: {
          required: true,
          message: '请选择用券时间',
          trigger: 'change'
        },
        limit_cate: { validator: validateCate, trigger: 'change' },
        limit_goods: { validator: validateGoods, trigger: 'change' },
        company_id: { validator: validateCompany, trigger: 'change' },
        start_time: { validator: validateStartTime, trigger: 'change' },
        end_time: { validator: validateEndTime, trigger: 'change' },
        top: { required: true, message: '请输入数字', validator: valiDateNumber, trigger: 'blur' },
        coupon_type: { required: true },
        use_limit: { required: true },
        send_type: { required: true },
        get_identity: { required: true },
        user_id: { validator: validateUser, trigger: 'change' },
        time_limit: { required: true },
        get_time: { validator: validateGetTime, trigger: 'change' },
        full: { validator: validateFull, trigger: 'change' }
      },
      disableOptions: [],
      goodsOptions: [],
      base_company: [],
      base_user: []
    }
  },
  created () {
    let { id } = this.$route.query
    this.id = id
    this.navTitle = this.$t(id ? 'menu.EditRedPackit' : 'menu.AddRedPackit')
    this.getSelectOptions()
    this.getBaseCompany()
    this.getBaseUser()
    if (!id) return
    this.editFormInfo({ id }, 'get')
  },
  methods: {
    async getBaseCompany () {
      let { data: company } = await this.$api.getBaseCompany()
      this.base_company = company
    },
    async getBaseUser () {
      let { data: user } = await this.$api.getBaseAllUser()
      this.base_user = user
    },
    /**
     * @method 获取下拉列表的值
     */
    getSelectOptions () {
      this.$api.getRedPakitOptions().then((res) => {
        if (res.code === 200) {
          this.disableOptions = res.data.limit_cate.map((item) => {
            item.id = parseInt(item.id)
            return item
          })
          this.goodsOptions = res.data.limit_goods.map((item) => {
            item.id = parseInt(item.id)
            return item
          })
        }
      })
    },
    redMarketChange (val, key) {
      if (val === 1 && key === 'coupon_type') {
        // 卡券类型选择为【礼品券】
        // 核销类型【type】为【线下核销】
        // 限用类型【limit_type】为【无限用】
        this.ruleForm.type = 2
        this.ruleForm.limit_type = 0
      }
      if (val === 1 && key === 'use_limit') {
        // 使用条件选择为【无门槛】
        // 消费金额【full】为【空】
        this.ruleForm.full = ''
      }
      if (val === 2 && key === 'type') {
        // 核销类型选择为【线下核销】
        // 限用类型【limit_type】为【无限用】
        this.ruleForm.limit_type = 0
      }
      if (val > 0 && key === 'send_type') {
        // 派发方式选择为【员工手动派发】【系统自动派发】
        // 每人限领次数【time_limit】为【不限次数】
        this.ruleForm.time_limit = 0
        if (val === 2) {
          // 派发方式选择为【系统自动派发】
          // 卡券数量【number】为【1】
          // 领取身份【get_identity】为【不限制，所有人可领取】
          this.ruleForm.number = 1
          this.ruleForm.get_identity = 0
        }
      }
    },
    /**
     * @method 提交时验证表单并判断是编辑还是添加
     */
    submitForm () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let { ruleForm } = this
          let { id } = this
          ruleForm.start_time = ruleForm.start_time
            ? moment(ruleForm.start_time).format('YYYY-MM-DD HH:mm:ss')
            : ''
          ruleForm.end_time = ruleForm.end_time
            ? moment(ruleForm.end_time).format('YYYY-MM-DD HH:mm:ss')
            : ''
          if (!id) {
            this.addFormInfo(ruleForm)
          } else {
            ruleForm.id = id
            this.editFormInfo(ruleForm, 'save')
          }
        } else {
          return false
        }
      })
    },

    /**
     * @method 编辑、回显卡券信息
     */
    editFormInfo (ruleForm, type) {
      this.$api.updateRedPackitStatus(ruleForm).then((res) => {
        if (res.code === 200) {
          if (type === 'get') {
            let { data } = res
            if (
              data.limit_goods.length > 0 &&
              typeof data.limit_type === 'object'
            ) {
              this.ruleForm.limit_goods = data.limit_goods.map((item) =>
                parseFloat(item)
              )
            }
            data.company_id = data.counpon_company
            data.user_id = data.coupon_user || []
            data.end_time = data.end_time ? new Date(data.end_time) : ''
            data.start_time = data.start_time ? new Date(data.start_time) : ''
            for (let key in this.ruleForm) {
              this.ruleForm[key] = data[key]
            }
          } else {
            this.$message.success(this.$t('tips.successSave'))
            this.$router.back(-1)
          }
        }
      })
    },

    /**
     * @method 添加卡券信息
     */
    addFormInfo (ruleForm) {
      console.log('添加')
      this.$api.addRedPackitInfo(ruleForm).then((res) => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success(this.$t('tips.successSave'))
          this.$router.back(-1)
        }
      })
    },
    /**
     * @method 返回上一页
     */
    goBack () {
      this.$router.back(-1)
    }
  },
  watch: {
    ruleForm (newValue, oldValue) {
      console.log(newValue, oldValue)
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-add-redpackit {
  width: 100%;
  .el-form-item {
    margin-bottom: 24px;
  }
  .last-form-item {
    margin-top: 30px;
  }
  .item-tips {
    margin-left: 120px;
    margin-bottom: 24px;
    color: #999999;
  }
  .el-input,
  .el-input-number,
  .el-cascader,
  .el-select {
    width: 300px;
  }
  .el-input-number.mini {
    width: 100px;
  }
  .el-textarea {
    width: 600px;
  }
}
</style>
